package ren.kane.phoenix.util.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author renrk(1275) on 2019-07-31 9:34 AM
 **/
public class SerialTest2 {

    private static final String TMP_FILE = "serialtest2.txt";


    /**
     * 将Box对象通过序列化，保存到文件中
     */
    private static void testWrite() {
        try {
            // ObjectOutputStream中，只能写入“基本数据”或“支持序列化的对象”
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("dir", TMP_FILE)));
            // Box1 box = new Box1("desk", 80, 50);
            Box2 box = new Box2("desk", 80, 50);
            objectOutputStream.writeObject(box);
            System.out.println("testWrite box: " + box);
            // box = new Box1("room", 100, 90);
            box = new Box2("room", 100, 90);
            objectOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从文件中读取出“序列化的Box对象”
     */
    private static void testRead() {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("dir", TMP_FILE)));
            // Box1 box = (Box1) objectInputStream.readObject();
            Box2 box = (Box2) objectInputStream.readObject();
            System.out.println("testRead box: " + box);
            objectInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testWrite();
        testRead();
    }
}
